<?php
	namespace app\index\controller;

	use \think\Db;

	class Order extends Base{
		public function index(){

		}

		public function add(){

			/*提交订单回显页面API*/

			try{

				if($this->method=='post'){

					$id=(int)input('post.id');

					$num=(int)input('post.num');

					$pid=input('post.pid');

					$carId=input('post.carId');

					$goods=[];

					$user=$this->getUser();
					/*获取用户信息*/

					if(!$user){
						$this->json(['code'=>0,'msg'=>'您还未登录！']);
					}

					// 判断是购物车提交还是商品详情页提交
					if($carId){

						// 购物车提交页面
						$carts=DB::name('carts')->where(['carts_id'=>['in',$carId],'carts_userId'=>$user['u_id']])->select();

						if($carts){
							$gids=array_column($carts,'carts_goodsId');

							$skuIds=array_column($carts,'carts_proId');

							$row=Db::name('goods')->field('g_id,g_freight,g_isSale,g_dataFlag,g_isSpec,g_limitNum,g_stock')->where(['g_id'=>['in',$gids]])->select();
							// 查询购物车下的商品
							$row2=[];

							foreach($row as $k=>$v){
								$row2[$v['g_id']]=$v;
							}

							$row=Db::name('goodsorder')->field('go_goodsId,sum(go_goodsNum)')->where(['go_goodsId'=>['in',$gids],'go_userId'=>$user['u_id'],'go_status'=>['<>',3]])->group('go_goodsId')->select();
							/*
							将用户购买的商品数量统计出来用于判断限购
							 */

							$buy=[];

							foreach($row as $k=>$v){
								// 重新拼凑下key,让商品的id作为key，方便下面使用
								$buy[$v['go_goodsId']]=$v['sum(go_goodsNum)'];
							}

							$row=Db::name('goods_property')->where(['pro_id'=>['in',$skuIds]])->select();
							// 将购物车商品对应的sku查询出来

							$sku=[];

							foreach($row as $k=>$v){
								$sku[$v['pro_id']]=$v;
							}


							foreach($carts as $k=>$v){

								// 将购物车的对应的商品拼凑出来

								if(isset($row2[$v['carts_goodsId']])){

									$data=$row2[$v['carts_goodsId']];

									$data['num']=$v['carts_goodsNum'];

									if(isset($buy[$v['carts_goodsId']])){
										$data['buyNum']=$buy[$v['carts_goodsId']];
									}else{
										$data['buyNum']=0;
									}

									$data['sku']=$v['carts_attr'];

									$data['g_name']=$v['carts_goodsName'];

									$data['g_icon']=$v['carts_goodsIcon'];

									$data['g_money']=$v['carts_pric'];

									if($v['carts_proId']!=0){
										//判断该购物车的商品是否有规格
											
										if(isset($sku[$v['carts_proId']])){
											
											$data['g_stock']=$sku[$v['carts_proId']]['pro_stock'];

											$data['g_money']=$sku[$v['carts_proId']]['pro_price'];

										}else{

											/*
											如果该购物车下的商品有规格且，且该规格id不存在数据库中，就改变该商品的状态
											 */

											$data['g_isSale']=-1;

										}

									}
									
									$goods[]=$data;


								}

							}

						}

						
					}else if($id){

						// 商品详情页提交

						if($num<1){
							$num=1;
						}

						$goods=Db::name('goods')->field('g_id,g_name,g_icon,g_money,g_freight,g_isSale,g_dataFlag,g_isSpec,g_limitNum,g_stock')->where(['g_id'=>$id,'g_isSale'=>1,'g_dataFlag'=>1])->select();

						if($goods){

							$buyNum=Db::name('goodsorder')->where(['go_goodsId'=>$id,'go_status'=>['<>',3],'go_userId'=>$user['u_id']])->count();

							$goods[0]['sku']='';

							$goods[0]['buyNum']=$buyNum;

							$goods[0]['num']=$num;

							if($goods[0]['g_isSpec']==1){

								// 判断该商品是否有规格

								$attr=Db::name('goods_property')->where(['pro_goodsId'=>$id])->find($pid);

								if(!$attr){
									// 判断该商品规格是否存在

									$goods=[];

								}

								$goods[0]['sku']=$attr['pro_spec'];

								$goods[0]['g_stock']=$attr['pro_stock'];

								$goods[0]['g_money']=$attr['pro_price'];

							}

							
						}
					}

					if(!$goods){
						$this->json(['code'=>0,'msg'=>'该页面已失效']);
					}

					$time=time();

					$field='c_id,c_name,c_money,c_above_money,c_shop_limit,c_startTime,c_endTime';

					$coupons=[];

					$disabled_coupons=[];

					$row=Db::name('coupons_code')->field($field)->where(['c_startTime'=>['<=',$time],'c_endTime'=>['>=',$time],'c_status'=>1,'c_userId'=>$user['u_id']])->select();


					foreach($row as $k=>$v){

						$ids=explode(',',$v['c_shop_limit']);

						$data=['id'=>$v['c_id'],'name'=>$v['c_name'],'condition'=>"满{$v['c_above_money']}元可用",'startAt'=>$v['c_startTime'],'endAt'=>$v['c_endTime'],'description'=>'','value'=>$v['c_money']*100,'valueDesc'=>"{$v['c_money']}元",'reason'=>'该商品不可用'];
						// 重新拼凑一下数组字段，用于前端框架使用
						
						$use=true;

						foreach($goods as $k2=>$v2){
							// 循环需要购买的商品

							$price=$v2['g_money']*$v2['num'];

							if($v['c_shop_limit']!=''){
								$bool=in_array($v2['g_id'],$ids);
							}else{
								$bool=true;
							}
							


							// 判断该优惠券是否可用
							if( ($v['c_shop_limit']!='' && $price>=$v['c_above_money']) || ($bool && $price>=$v['c_above_money']) ){
								// 可用优惠券

								$data['reason']='';

								$coupons[]=$data;

								$use=true;

								break;
							}else{

								// 不可用的优惠券

								if($bool){
									// 如为true则不可用的原因是未达到指定金额,否则就是该商品不可用

									$data['reason']='未达到指定金额';

								}

								$use=false;

							}

						}

						if(!$use){
							// 如果use为false说明该优惠券在不能用于该商品

							$disabled_coupons[]=$data;
						}



					}

					$row=Db::name('address')->field('a_id,a_name,a_tel,a_sheng,a_shi,a_qu,a_address,a_default')->where(['a_userId'=>$user['u_id']])->select();

					$address=[];

					foreach($row as $k=>$v){
						$data=['id'=>$v['a_id'],'name'=>$v['a_name'],'tel'=>$v['a_tel'],'address'=>"{$v['a_sheng']} {$v['a_shi']} {$v['a_qu']} {$v['a_address']}"];

						if($v['a_default']==1){
							$data['isDefault']=true;
						}else{
							$data['isDefault']=false;
						}

							$address[]=$data;
						
					}

					return $this->data(['goods'=>$goods,'coupons'=>$coupons,'address'=>$address,'disabled_coupons'=>$disabled_coupons]);

				}else{
					echo '拒绝访问';
				}

			}catch(\Exception $e){
				return $this->err($e);
			}

		}

		public function sub(){
			// 提交订单处理程序
			
			try{
				if($this->method=='post'){

					$id=(int)input('post.id');

					$num=(int)input('post.num');

					$pid=(int)input('post.pid');

					$carId=input('post.carId');

					$couId=(int)input('post.couId');

					$aid=input('post.aid');

					$user=$this->getUser();

					if(!$user){
						$this->json(['msg'=>'你还未登录','code'=>0]);
					}

					$time=time();

					$coupon=Db::name('coupons_code')->where(['c_id'=>$couId,'c_startTime'=>['<=',$time],'c_endTime'=>['>=',$time],'c_status'=>1,'c_userId'=>$user['u_id']])->find();

					$cou_goodsId=[];

					$couMoney=0;

					if($coupon){

						if($coupon['c_shop_limit']!=''){
							$cou_goodsId=explode(',',$coupon['c_shop_limit']);
						}
						
					}

					// 判断是提交购物车还是单个商品
					if($carId){
						// 购物车

						$carts=Db::name('carts')->where(['carts_id'=>['in',$carId],'carts_userId'=>$user['u_id']])->select();

						if(!$carts){
							$this->json(['code'=>0,'msg'=>'页面已失效']);
						}
						

						$gids=array_column($carts,'carts_goodsId');

						$skuIds=array_column($carts,'carts_proId');

						$row=Db::name('goods')->field('g_id,g_money,g_freight,g_isSale,g_dataFlag,g_isSpec,g_limitNum,g_stock')->where(['g_id'=>['in',$gids]])->select();

						$goods=[];

						foreach($row as $k=>$v){
							$goods[$v['g_id']]=$v;
						}

						$row=Db::name('goodsorder')->field('go_goodsId,sum(go_goodsNum)')->where(['go_goodsId'=>['in',$gids],'go_userId'=>$user['u_id'],'go_status'=>['<>',3]])->group('go_goodsId')->select();

						// 查询该用户购买该商品的数量，用于判断是否超出限购

						$buyGoods=[];

						foreach($row as $k=>$v){
							$buyGoods[$v['go_goodsId']]=$v['sum(go_goodsNum)'];
						}


						$row=Db::name('goods_property')->where(['pro_id'=>['in',$skuIds]])->select();

						// 查询购物车里面的商品规格
						
						$sku=[];

						foreach($row as $k=>$v){
							$sku[$v['pro_id']]=$v;
						}

						$buy=[];

						$totalMoney=0;

						$freight=0;

						foreach($carts as $k=>$v){

							if(isset($goods[$v['carts_goodsId']])){
								
								$good=$goods[$v['carts_goodsId']];

								if($good['g_dataFlag']==-1 || $good['g_isSale']==-1){
									// 判断商品是否上架，并且是可购买的商品
									continue;

								}

								if(isset($buyGoods[$v['carts_goodsId']]) && $good['g_limitNum']!=0 && $buyGoods[$v['carts_goodsId']]+$v['carts_goodsNum']>$good['g_limitNum']){

									// 判断该购物车的商品是否超出限购

									continue;
								}

								// 判断商品是否有规格
								if($goods[$v['carts_goodsId']]['g_isSpec']==1){

									if(isset($sku[$v['carts_proId']])){

										if($v['carts_goodsNum']>$sku[$v['carts_proId']]['pro_stock']){

											// 判断是否超出库存
											continue;
										}

									}else{

										// 如果商品有规格，并且购物车的规格id不存在则该类商品不能购买
										continue;
									}

								}else{

									if($v['carts_goodsNum']>$goods[$v['carts_goodsId']]['g_stock']){

										// 判断是否超出库存
										
										continue;
									}

								}

								$totalMoney+=$v['carts_pric']*$v['carts_goodsNum'];


								$buy[]=['go_orderId'=>'','go_goodsId'=>$good['g_id'],'go_goodsName'=>$v['carts_goodsName'],'go_goodsNum'=>$v['carts_goodsNum'],'go_goodsPric'=>$v['carts_pric'],'go_goodsAttr'=>$v['carts_attr'],'go_goodsImage'=>$v['carts_goodsIcon'],'go_userId'=>$user['u_id'],'go_actualPric'=>$v['carts_pric']];

								if($good['g_freight']>$freight){
									$freight=$good['g_freight'];
								}



							}
						}
					}else{
						// 单个商品
						
						$goods=Db::name('goods')->field('g_id,g_name,g_icon,g_money,g_freight,g_isSale,g_dataFlag,g_isSpec,g_limitNum,g_stock')->where(['g_id'=>$id])->find();

						if(!$goods){
							$this->json(['code'=>0,'msg'=>'页面已失效']);
						}

						if($goods['g_isSale']==-1 || $goods['g_dataFlag']==-1){

							$this->json(['code'=>0,'msg'=>'该商品已下架或失效']);

						}

						if($num<=0){
							$num=1;
						}

						$buyGoods=Db::name('goodsorder')->where(['go_goodsId'=>$id,'go_userId'=>$user['u_id'],'go_status'=>['<>',3]])->count();

						if($goods['g_limitNum']!=0 && $buyGoods+$num>$goods['g_limitNum']){

							// 判断是否超出限购数量

							$this->json(['code'=>0,'msg'=>'购买数量超过了宝贝的限购数']);
						}

						if($goods['g_isSpec']==1){

							// 判断该商品是否有规格

							$sku=Db::name('goods_property')->where(['pro_id'=>$pid,'pro_goodsId'=>$id])->find();

							if(!$sku){
								$this->json(['code'=>0,'msg'=>'该商品已下架或失效']);
							}

							if($num>$sku['pro_stock']){
								$this->json(['code'=>0,'msg'=>'库存不足']);
							}
							// 判断购买数量是否超出库存
							$price=$sku['pro_price'];

							$attr=$sku['pro_spec'];
							
						}else{

							if($num>$goods['g_stock']){
								$this->json(['code'=>0,'msg'=>'库存不足']);
							}

							$price=$goods['g_money'];

							$attr='';

						}

						$buy=[
							['go_orderId'=>'','go_goodsId'=>$id,'go_goodsName'=>$goods['g_name'],'go_goodsNum'=>$num,'go_goodsPric'=>$price,'go_goodsAttr'=>$attr,'go_goodsImage'=>$goods['g_icon'],'go_userId'=>$user['u_id'],'go_actualPric'=>$price]
						];

						$totalMoney=$price*$num;

						$freight=$goods['g_freight'];

						$gids=[$id];

					}

					$address=Db::name('address')->where(['a_userId'=>$user['u_id'],'a_id'=>$aid])->find();

					if(!$address){
						$this->json(['code'=>0,'msg'=>'请设置收货地址']);
					}

					$details_address=$address['a_sheng'].','.$address['a_shi'].','.$address['a_qu'].','.$address['a_address'];

					$disBool=false;//用于判断是否使用成功优惠券

					if($coupon && (empty($cou_goodsId) || array_intersect($gids,$cou_goodsId)) && $totalMoney>=$coupon['c_above_money'] ){

						/*
							如果优惠券有数据，并且没有商品的限制,或者购买的商品在优惠券可用范围之内,并满足优惠券使用条件

							array_intersect($gids,$cou_goodsId)：
							取购买商品id和优惠券约束的商品id的交集，如果他们有交集说明该优惠券可用
						 */

							$couMoney=$coupon['c_money'];

							$disBool=true;

							foreach($buy as $k=>$v){

								$price=$v['go_goodsPric']*$v['go_goodsNum'];

								$price-=$couMoney;

								if($price<0){

									$couMoney=0-$price;

									$buy[$k]['go_actualPric']=0;

								}else{

									// 如果优惠后的金额不小于0说明优惠券的金额已经全部使用了，就跳出循环

									$buy[$k]['go_actualPric']=round($price/$v['go_goodsNum'],2);

									break;
								}

							}

					}

					$disMoney=$totalMoney-$couMoney;

					if($disMoney<0){
						$disMoney=0;
					}

					$name=$osn = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);

					
					
					$data=[
						'o_name'=>$name,
						'o_userId'=>$user['u_id'],
						'o_userName'=>$user['u_username'],
						'o_goodsMoney'=>$totalMoney+$freight,
						'o_goodsFreight'=>$freight,
						'o_totalMoney'=>$disMoney,
						'o_theTel'=>$address['a_tel'],
						'o_theName'=>$address['a_name'],
						'o_theAddress'=>$details_address,
						'o_payType'=>1,
						'o_payFrom'=>3,
						'o_createTime'=>$time,
						'o_remnant_freight'=>$freight,
					];

					/*
					优惠券优惠之后的金额未更改
					 */

					Db::startTrans();

					$res=Db::name('order')->insertGetId($data);

					foreach($buy as $k=>$v){
						$buy[$k]['go_orderId']=$res;
					}

					$res2=Db::name('goodsorder')->insertAll($buy);

					if($carId){
						$res3=Db::name('carts')->where(['carts_id'=>['in',$carId],'carts_userId'=>$user['u_id']])->delete();
					}

					if($disBool){
						$res4=Db::name('coupons_code')->where(['c_id'=>$coupon['c_id']])->update(['c_useTime'=>$time,'c_status'=>2]);
					}


					if($res && $res2){
						Db::commit();

						$this->json(['code'=>1,'msg'=>$name]);
					}else{
						Db::rollback();

						$this->json(['code'=>0,'msg'=>'提交失败']);
					}
				}else{
					echo '拒绝访问';
				}
			}catch(\Exception $e){

				Db::rollback();
				return $this->err($e);
			}

		}

		public function pay(){
			// 订单支付
			try{
				if($this->method=='post'){
					$oname=input('post.oname');

					$pass=input('post.pass');

					$user=$this->getUser();

					if(!$user){
						$this->json(['code'=>0,'msg'=>'您还未登录！']);
					}

					$order=Db::name('order')->where(['o_name'=>$oname])->find();

					if(!$order || $order['o_status']==-1){
						$this->json(['code'=>0,'msg'=>'该订单已失效']);
					}

					if($order['o_isPay']==1){
						$this->json(['code'=>0,'msg'=>'该订单已支付']);
					}

					if($pass==''){
						$this->json(['code'=>0,'msg'=>'请输入您的支付密码']);
					}
					
					$user=Db::name('user')->find($user['u_id']);

					$pass=md5($pass);

					if($user['u_paypass']!=$pass){
						$this->json(['code'=>0,'msg'=>'支付密码不正确']);
					}

					if($user['u_money']<$order['o_totalMoney']){
						$this->json(['code'=>0,'msg'=>'你的账户余额不足']);
					}

					$time=time();

					Db::startTrans();

					$res=Db::name('order')->where(['o_name'=>$oname])->update(['o_isPay'=>1,'o_payTime'=>$time,'o_payFrom'=>3]);

					$res2=true;

					if($order['o_totalMoney']>0){
						// 如果需要支付的金额大于0，就往用户的账户扣除余额
						$money=0-$order['o_totalMoney'];

						$res2=Db::name('user')->where(['u_id'=>$user['u_id']])->setInc('u_money',$money);

						$resMoney=$user['u_money']-$order['o_totalMoney'];

						$res3=Db::name('money_datails')->insert(['m_note'=>'手机端订单支付，单号【'.$order['o_name'].'】','m_userId'=>$user['u_id'],'m_userName'=>$user['u_username'],'m_time'=>$time,'m_type'=>5,'m_czMoney'=>$order['o_totalMoney'],'m_resMoney'=>$resMoney]);
					}

					if($res && $res2){
						Db::commit();

						$this->json(['code'=>1,'msg'=>'支付成功']);
					}

					Db::rollback();

					$this->json(['code'=>0,'msg'=>'支付失败']);

					
				}else{
					echo '拒绝访问';
				}
			}catch(\Exception $e){

				Db::rollback();

				return $this->err($e);
			}
		}
	}
?>